package Concurrency2.Chapter03_CAS_Atomic;

import sun.misc.Unsafe;

import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;

/**
 * Instruction：使用Unsafe提供的cas进行无锁编程
 * <p>
 * Author：@author MaLi
 */
public class T02_CasAutoIncrement {

    public static void main(String[] args) throws InterruptedException {
        //0, 准备
        Some some = new Some();
        Unsafe unsafe = Utils4Unsafe.getUnsafe();
        ArrayList<Thread> threads = new ArrayList<>(10);
        CountDownLatch count = new CountDownLatch(10);

        //1, 创建10个线程
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(() -> {
                System.out.println("ThreadName" + Thread.currentThread().getName() + " Start...");
                for (int j = 0; j < 1000000; j++) {
                    try {
                        boolean changed = false;
                        do {
                            changed = unsafe.compareAndSwapObject(some, unsafe.objectFieldOffset(Some.class.getDeclaredField("data")), some.getData(), some.getData() + 1);
                        }
                        while (!changed);
                    } catch (NoSuchFieldException e) {
                        throw new RuntimeException(e);
                    }
                }
                count.countDown();
                System.out.println("ThreadName" + Thread.currentThread().getName() + " End...");
            });
            threads.add(thread);
        }

        for (Thread thread : threads) {
            thread.start();
        }
        count.await();
        System.out.println(some.getData());

    }

    private static class Some {
        private Integer data;

        public Some() {
            this.data = 0;
        }

        public Integer getData() {
            return data;
        }

        public void setData(Integer data) {
            this.data = data;
        }
    }
}
